def centuryFromYear(year):
return ((year-1) // 100) + 1
def checkPalindrome(inputString):
return inputString == inputString[::-1]
def adjacentElementsProduct(inputArray):
max = inputArray[0] * inputArray[1]
for i in range(len(inputArray) - 1):
if inputArray[i] * inputArray[i+1] > max:
max = inputArray[i] * inputArray[i+1]
for i in range(1, (n*2)-1, 2):
def makeArrayConsecutive2(statues):
return max(statues) - min(statues) - len(statues) + 1
def almostIncreasingSequence(sequence):
while i < len(sequence) - 1:
if not sequence[i] < sequence[i + 1]:
if increasingSequence(sequence[:i] + sequence[i+1:]) or \
increasingSequence(sequence[:i+1] + sequence[i+2:]):
def increasingSequence(sequence):
for i in range(len(sequence) - 1):
if not sequence[i] < sequence[i + 1]:
def matrixElementsSum(matrix):
for row in range(1, len(matrix)):
for room in range(len(matrix[row])):
if matrix[row - 1][room] == 0:
def allLongestStrings(inputArray):
length = max([len(word) for word in inputArray])
result = [word for word in inputArray if len(word) == length]
def commonCharacterCount(s1, s2):
top = [int(x) for x in string[:len(string)//2]]
bottom = [int(x) for x in string[len(string)//2:]]
return sum(top) == sum(bottom)
treePositions = [x for x in range(len(a)) if a[x] == -1]
people = sorted([x for x in a if x != -1])
for tree in treePositions:
def reverseParentheses(s):
match = re.search("\([^()]*\)", s)
match_string = match.group(0)[1: len(match.group(0)) - 1]
reversed_match_string = match_string[::-1]
s = s[:match.start()] + reversed_match_string + s[match.end():]
picture = ["*" + string + "*" for string in picture]
picture = [("*" * len(picture[0]))] + picture + [("*" * len(picture[0]))]
diff = [i for i in range(len(a)) if a[i] != b[i]]
b[diff[0]], b[diff[1]] = b[diff[1]], b[diff[0]]
def arrayChange(inputArray):
for i in range(1, len(inputArray)):
if inputArray[i-1] >= inputArray[i]:
difference = inputArray[i-1] - inputArray[i]
inputArray[i] += difference + 1
def palindromeRearranging(inputString):
inputList = sorted(inputString)
while len(inputList) > 1:
if inputList[0] == inputList[1]:
return len(inputList) == 0 or not foundMiddle
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
sameHands = yourLeft == friendsLeft and yourRight == friendsRight
differentHands = yourLeft == friendsRight and yourRight == friendsLeft
return sameHands or differentHands
def arrayMaximalAdjacentDifference(inputArray):
for i in range(len(inputArray) - 1):
diffs.append(abs(inputArray[i] - inputArray[i + 1]))
def isIPv4Address(inputString):
strings = [string for string in inputString.split('.')]
if not string.isdecimal():
nums = [int(num) for num in strings]
return max(nums) <= 255 and min(nums) >= 0 and len(nums) == 4
def avoidObstacles(inputArray):
for length in range(2, max(inputArray) + 2):
while jump < (max(inputArray) + length):
for row in range(1, len(image) - 1):
for pixel in range(1, len(image[row]) - 1):
total = (image[row - 1][pixel - 1]
+ image[row - 1][pixel + 1]
+ image[row + 1][pixel - 1]
+ image[row + 1][pixel + 1])
RIGHT = len(matrix[0]) - 1
for row in range(len(matrix)):
for cell in range(len(matrix[row])):
outRow[cell] += matrix[row - 1][cell]
outRow[cell] += matrix[row + 1][cell]
outRow[cell] += matrix[row][cell - 1]
outRow[cell] += matrix[row][cell + 1]
if row != TOP and cell != LEFT:
outRow[cell] += matrix[row - 1][cell - 1]
if row != TOP and cell != RIGHT:
outRow[cell] += matrix[row - 1][cell + 1]
if row != BOTTOM and cell != LEFT:
outRow[cell] += matrix[row + 1][cell - 1]
if row != BOTTOM and cell != RIGHT:
outRow[cell] += matrix[row + 1][cell + 1]
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return [x if x != elemToReplace else substitutionElem for x in inputArray]
return all((True if digit in ('0', '2', '4', '6', '8') else False for digit in str(n)))
return name.replace("_", "").isalnum() and not name[0].isdigit()
def alphabeticShift(inputString):
return ''.join([chr(ord(x) + 1) if x != 'z' else 'a' for x in inputString])
def chessBoardCellColor(cell1, cell2):
color1 = ((ord(cell1[0]) - ord('A')) + ord(cell1[1]) - ord('1')) % 2 == 0
color2 = ((ord(cell2[0]) - ord('A')) + ord(cell2[1]) - ord('1')) % 2 == 0
def circleOfNumbers(n, firstNumber):
return (firstNumber + (n / 2)) % n
def depositProfit(deposit, rate, threshold):
while deposit < threshold:
deposit *= 1 + (rate / 100)
def absoluteValuesSumMinimization(a):
total = sum([abs(a[i] - num) for i in range(len(a))])
sums[total] = min(num, sums[total])
def stringsRearrangement(inputArray):
permutations = itertools.permutations(inputArray)
for array in permutations:
if testArrangement(array):
def testArrangement(array):
for i in range(len(array) - 1):
if sum([a != b for a, b in zip(array[i], array[i + 1])]) != 1:
def extractEachKth(inputArray, k):
return [inputArray[x] for x in range(len(inputArray)) if (x + 1) % k != 0]
def firstDigit(inputString):
def differentSymbolsNaive(s):
def arrayMaxConsecutiveSum(inputArray, k):
sums = [sum(inputArray[:k])]
for i in range(1, len(inputArray) - k + 1):
sums.append(sums[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
def growingPlant(upSpeed, downSpeed, desiredHeight):
while height < desiredHeight:
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
if weight1 <= maxW and (weight2 > maxW or value1 >= value2):
if weight2 <= maxW and (weight1 > maxW or value2 >= value1):
def longestDigitsPrefix(inputString):
for char in range(len(inputString)):
if not inputString[char].isdigit():
return inputString[:char]
n = sum((int(digit) for digit in str(n)))
def bishopAndPawn(bishop, pawn):
return abs(ord(bishop[0]) - ord(pawn[0])) == abs(ord(bishop[1]) - ord(pawn[1]))
def isBeautifulString(inputString):
for letter in range(ord('a'), ord('z')):
if inputString.count(chr(letter)) < inputString.count(chr(letter + 1)):
def findEmailDomain(address):
return address[address.rfind('@') + 1:]
if st == st[::-1]: # Check for initial palindrome
while subStr != subStr[::-1]: # while substring is not a palindrome
return st + st[index - 1::-1]
def electionsWinners(votes, k):
current_winner = max(votes)
if k > 0 and candidate + k > current_winner:
if k == 0 and candidate == current_winner and votes.count(candidate) == 1:
def isMAC48Address(inputString):
hex_chars = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'A', 'B', 'C', 'D', 'E', 'F',
'a', 'b', 'c', 'd', 'e', 'f')
groups = inputString.split('-')
if not all((len(group) == 2 for group in groups)):
if not all((group[0] in hex_chars and group[1] in hex_chars for group in groups)):
for char in range(1, len(s)):
if s[char] == s[char - 1]:
output.append(str(count) + s[char - 1])
output.append(s[char - 1])
if s[len(s) - 1] == s[len(s) - 2]:
output.append(str(count) + s[len(s) - 1])
output.append(s[len(s) - 1])
# Starting at the top left, going counter-clockwise
if ord(cell[0]) >= ord("b") and ord(cell[1]) <= ord("6"):
if ord(cell[0]) >= ord("c") and ord(cell[1]) <= ord("7"):
if ord(cell[0]) >= ord("c") and ord(cell[1]) >= ord("2"):
if ord(cell[0]) >= ord("b") and ord(cell[1]) >= ord("3"):
if ord(cell[0]) <= ord("g") and ord(cell[1]) >= ord("3"):
if ord(cell[0]) <= ord("f") and ord(cell[1]) >= ord("2"):
if ord(cell[0]) <= ord("f") and ord(cell[1]) <= ord("7"):
if ord(cell[0]) <= ord("g") and ord(cell[1]) <= ord("6"):
for digit in range(len(num)):
output = num[:digit] + num[digit + 1:]
if int(output) > int(highest):
if ord("A") <= ord(char) <= ord("Z") or ord("a") <= ord(char) <= ord("z"):
if len(word) > len(longest):
if len(word) > len(longest):
if not (groups[0].isdigit() and groups[1].isdigit()):
if int(groups[0]) > 23 or int(groups[1]) > 59:
def sumUpNumbers(inputString):
num = int("".join(current_num))
num = int("".join(current_num))
def differentSquares(matrix):
for row in range(len(matrix) - 1):
for cell in range(len(matrix[row]) - 1):
square = ((matrix[row][cell], matrix[row][cell + 1]),
(matrix[row + 1][cell], matrix[row + 1][cell + 1]))
def digitsProduct(product):
# New idea: add product to factors
# while max(factors) > 10: split that num into factors
factored = findFactors(max(factors))
factors.remove(max(factors))
while factors.count(3) >= 2:
while factors.count(2) > 2:
while factors.count(2) > 1:
while 2 in factors and 3 in factors:
return int("".join(map(str, sorted(factors))))
for i in range(2, int(n ** 0.5) + 1):
while "{}({})".format(name, k) in outnames:
name = "{}({})".format(name, k)
def messageFromBinaryCode(code):
for i in range(0, len(code), 8):
letter = chr(int(code[i:i + 8], 2))
spiral = [[0 for i in range(n)] for j in range(n)]
for num in range(1, (n * n) + 1):
if cell != n - 1 and spiral[row][cell + 1] == 0:
if row != n - 1 and spiral[row + 1][cell] == 0:
if cell != 0 and spiral[row][cell - 1] == 0:
if row != 0 and spiral[row - 1][cell] == 0:
match = [i for i in range(1, 10)]
for column_index in range(9):
column = [grid[row_index][column_index] for row_index in range(9)]
if sorted(column) != match:
for row in range(0, 9, 3):
for column in range(0, 9, 3):
box.extend(grid[row][column:column + 3])
box.extend(grid[row + 1][column:column + 3])
box.extend(grid[row + 2][column:column + 3])
# def isAdult(age, majority):
isAdult = lambda a, m: a >= m
def bishopAndPawn(bishop, pawn):
if ord(bishop[0]) == ord(pawn[0]):
bishop_elm = ord(bishop[0]) + int(bishop[1])
pawn_elm = ord(pawn[0]) + int(pawn[1])
return (bishop_elm + pawn_elm) % 2 == 0
"""Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the
(n - 1)-interesting polygon and appending 1-interesting polygons to its rim, side by side.
You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)
- For n = 2, the output should be shapeArea(n) = 5;
- For n = 3, the output should be shapeArea(n) = 13."""
# Case 1: If the polygon is 0-interesting, it has an area equal to zero.
# Case 2: If the polygon is 1-interesting, it has an area equal to one.
# Case 3: If the polygon is n-interesting, it has an area equal to the sum of the square of n
# and the square of n-1. A way that I thought of it (based on the picture provided) is the following:
# - n**2: Counted the number of the blue squares from the middle line upwards (INCLUDING the blue squares of the middle line).
# - (n-1)**2: Counted the number of the blue squares from the middle line downwards (EXCLUDING the blue squares of the middle line).
# Of course, you can easily check that the terms "upwards/downwards" could be inverted, without affecting the validity of your counting.
result = (n ** 2) + ((n - 1) ** 2)
"""Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size.
Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the
previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of
additional statues needed.
For statues = [6, 2, 3, 8], the output should be makeArrayConsecutive2(statues) = 3.
Ratiorg needs statues of sizes 4, 5 and 7."""
def makeArrayConsecutive2(statues):
# Step 1: We begin by creating a new array called "stat_arr", which will accommodate the sorted version of the original "statues" array.
stat_arr = sorted(statues)
# Step 2: Furthermore, we use the first element of the sorted array as our index (that will be used in the following steps).
# Step 3: We create an empty list called "result" to store our (numbered) missing statues.
# Step 4: We initiate a while-loop with the condition that the index from Step 2 is not equal to the last (hence largest) entry of
# the stat_arr. You must make sure that you add the "incrementation by 1" part to make the while loop proceed to the next element.
# Step 5: Here, using a simple if statement, we examine whether the i-th (integer) element is included in the stat_arr.
# If it is not, we append it to the result list. Otherwise, the loop continues.
# Step 6: Finally, we return the length/size of the result list, i.e. the number of our "missing" statues.
# return sum(eval(dir()[0]), [])
# return [x for l in eval(dir()[0]) for x in l]
# def twoArraysNthElement(array1, array2, n):
# return sorted(array1 + array2)[n]
# twoArraysNthElement = lambda a, b, n: sorted(a + b)[n]
# def divideAsLongAsPossible(n, d):
def bstFromPreorder(self, preorder):
root = TreeNode(preorder[0])
while i < len(preorder) and preorder[i] < root.val:
root.left = self.bstFromPreorder(preorder[1:i])
root.right = self.bstFromPreorder(preorder[i:])
preorder = [19, 4, 8, 11]
bst.bstFromPreorder(preorder)
def isBeautifulString(inputString):
counter = [inputString.count(i) for i in string.ascii_lowercase]
return counter[::-1] == sorted(counter)
def pixels(matrix, i, j):
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
for i in range(1, row - 1):
for j in range(1, col - 1):
arr.append(pixels(image, i, j))
def chessBoardCellColor(cell1, cell2):
cell1_elm = ord(cell1[0]) + int(cell1[1])
cell2_elm = ord(cell2[0]) + int(cell2[1])
return (cell1_elm + cell2_elm) % 2 == 0
for i in range(0, len(picture[0]) + 2):
for i in range(0, pic_len):
new_pic.append("*" + picture[i] + "*")
sulkyBoy = lambda x: not x
# *re.findall('...', 'abcdefghijklmno')
# >>> 'abc', 'def', 'ghi', 'jkl', 'mno'
# [0,0,"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
"0 0 abc def ghi jkl mno pqrs tuv wxyz".split()[int(i)]
for i in eval(dir()[0])[0]
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= prices[i + 1]:
while i < len(prices) - 1 and prices[i] <= prices[i + 1]:
max_profit += max_pri - min_pri
print(maxProfit([1, 2, 3, 4, 5, 6]))
A, = numpy.r_[eval(dir()[0])]
A[A > 0] = sorted(A[A > 0])
"""Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
- For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]."""
# Step 1: We begin by creating a counter, starting from 0, that will be used in the subsequent for-loop.
# Step 2: We also create a new array, called "a_sort", where we sort (in ascending order) all elements of the given array "a"
# that are not "trees" (i.e. do not have a value of -1).
a_sort = sorted([i for i in a if i != -1])
# Step 3: By implementing a for-loop, we investigate all elements of the given array "a" (NOT a_sort!) and check:
# if the element i in array "a" is equal to -1, the for-loop continues. Otherwise, the element i in array "a" should be
# the same as element j in array "a_sort" (starting from 0 index, as defined in step 1).
# You can think of it as working through elements of array "a", disregarding the "trees" (-1s) and sorting the rest
# of the elements in ascending order (as in a_sort).
# Step 4: The final step is the return of the modified array "a".
def arrayChange(inputArray):
"""Given two strings, find the number of common characters between them.
For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c"."""
def commonCharacterCount(s1, s2):
# Step 1: We create two lists, namely s1_l and s2_l, where we store the characters of strings s1 and s2 respectively.
# Step 2: We also create an empty list, where we are going to store all common characters.
# Step 3: Using a for-loop, we investigate the list of the first string, element by element.
# Step 4: If the i-th element from the list of the first string is also present in the list of the second string,
# we append it to the common array. BE CAREFUL: We must implement the s2_l.remove(i) to avoid double-counting.
# I checked myself and I can assure you that you can substitute s1_l for s2_l and vice versa (in the for-loop,
# the if statement and the double-counting term), without affecting the validity of your code.
# Step 5: Finally, we return the length of the common list, to find the number of the common characters
# between the two strings given.
# if any(i.isdigit() for i in s) and any(i.islower() for i in s) and any(i.isupper() for i in s) and len(s) >= 5:
# passwordCheck = lambda s: (any(i.isdigit()) and any(i.islower()) and any(i.isupper())) for i in s and len(s) > 4
# return len(s) > 4 and all(re.search(p, s) for p in ('[A-Z]', '\d', '[a-z]'))
passwordCheck = lambda s: len(s) > 4 and all(
re.search(i, s) for i in ("[A-Z]", "\d", "[a-z]")
# def fractionComparison(a, b):
(a, b), (c, d) = eval(dir()[0])
return "<" if r < 1 else ">" if r > 1 else "="
numpy.add(L[:-1:2], L[1::2])
else numpy.multiply(L[:-1:2], L[1::2])
numpy.add(L[:-1:2], L[1::2])
else numpy.multiply(L[:-1:2], L[1::2])
return (n // 10) + (n % 10)
def seatsInTheater(nCols, nRows, col, row):
return (nCols - col + 1) * (nRows - row)
def maxMultiple(divisor, bound):
for num in range(bound, 1, -1):
def circleOfNumbers(n, firstNumber):
return (firstNumber + (n // 2)) % n
return (hours // 10) + (hours % 10) + (minutes // 10) + (minutes % 10)
def phoneCall(min1, min2_10, min11, s):
if s <= min1 + (min2_10 * 9):
return (s // min2_10) + 1
def reachNextLevel(experience, threshold, reward):
return experience + reward >= threshold
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
if weight1 <= maxW and weight2 <= maxW:
return max(value1, value2)
def extraNumber(a, b, c):
def isInfiniteProcess(a, b):
return a > b or (a % 2 != b % 2)
def arithmeticExpression(a, b, c):
return a + b == c or a - b == c or a * b == c or a / b == c
def tennisSet(score1, score2):
if max(score1, score2) == 6 and min(score1, score2) < 5:
if 5 <= min(score1, score2) <= 6 and max(score1, score2) == 7:
def willYou(young, beautiful, loved):
return (young and beautiful) != loved
def metroCard(lastNumberOfDays):
if lastNumberOfDays == 30 or lastNumberOfDays == 28:
return n & ~(2 ** (k - 1))
binary_array = [bin(num)[2:].rjust(8, '0') for num in a]
out_string = ''.join(binary_array[::-1])
return int(out_string, 2)
array = list(range(a, b + 1))
binary_array = [bin(num) for num in array]
count_array = [binary.count('1') for binary in binary_array]
return int(binary[::-1], 2)
def secondRightmostZeroBit(n):
return 2 ** bin(n)[::-1].find('0', bin(n)[::-1].find('0') + 1)
return ((n >> 1) & 1431655765) | ((n << 1) & 2863311530)
def differentRightmostBit(n, m):
return 2 ** bin((n ^ m))[::-1].find('1')
def equalPairOfBits(n, m):
return 2 ** bin(~(n ^ m))[::-1].find('1')
def countSumOfTwoRepresentations2(n, l, r):
def magicalWell(a, b, n):
smart_student = (smart_student - 1) % 4
dumb_student = (dumb_student + 1) % 4
smart_student = (smart_student + 1) % 4
dumb_student = (dumb_student - 1) % 4
smart_student = (smart_student + 2) % 4
dumb_student = (dumb_student + 2) % 4
if smart_student == dumb_student:
def additionWithoutCarrying(param1, param2):
# Convert numbers to strings
# Pad both to the same length with zeroes (to the left of the numbers)
length = max(len(str2), len(str1))
str1 = str1.rjust(length, '0')
str2 = str2.rjust(length, '0')
for num1, num2 in zip(str1, str2):
result = str(int(num1) + int(num2))[-1]
return int(''.join(output))
for i in range(1, k + 1, 2):
for i in range(2, k + 1, 2):
def increaseNumberRoundness(n):
# Check for immediate rejection
if '0' not in string or len(string) < 2:
# Since we know there's a 0, if it's not on
# the left, then we know to accept
# If there is only one 0, it must be at the end, so reject.
if string.count('0') == 1:
# If there are any numbers between the first 0
# and the end of the string, then accept.
first_zero = string.find('0')
zero_sandwich = string[first_zero:]
return zero_sandwich.count('0') != len(zero_sandwich)
for i in range(length - 1):
value = int((value / 10) + 0.5)
return value * (10 ** magnitude)
def candles(candlesNumber, makeNew):
totalBurned += candlesNumber
leftovers += candlesNumber
candlesNumber = leftovers // makeNew
leftovers = leftovers % makeNew
def countBlackCells(n, m):
line_corner_cells = (gcd - 1) * 2
return line_cells + line_corner_cells
def arrayReplace(inputArray, elemToReplace, substitutionElem):
output = [elem if elem != elemToReplace else substitutionElem for elem in inputArray]
def firstReverseTry(arr):
return arr[-1:] + arr[1:-1] + arr[:1]
def concatenateArrays(a, b):
def removeArrayPart(inputArray, l, r):
return inputArray[:l] + inputArray[r + 1:]
middle = arr[len(arr) // 2] + arr[(len(arr) // 2) - 1]
middle = arr[len(arr) // 2]
right_middle = len(arr) // 2
middle_value = arr[right_middle] + arr[right_middle - 1]
return arr[:right_middle - 1] + [middle_value] + arr[right_middle + 1:]
def makeArrayConsecutive2(statues):
for i in range(min(statues), max(statues)):
def isSumOfConsecutive2(n):
while right <= (n // 2) + 1:
def squareDigitsSequence(a0):
while sequence[-1] not in sequence[:-1]:
for digit in str(sequence[-1]):
next_value += int(digit) ** 2
sequence.append(next_value)
def pagesNumberingWithInk(current, numberOfDigits):
numberOfDigits -= len(str(current))
next_digits = len(str(current + 1))
while numberOfDigits >= next_digits:
numberOfDigits -= next_digits
next_digits = len(str(current))
def comfortableNumbers(l, r):
for b in range(a + 1, r + 1):
a_sum = sum(int(digit) for digit in str(a))
b_sum = sum(int(digit) for digit in str(b))
if b <= a + a_sum and a >= b - b_sum:
all_factors = [count_factors(num) for num in range(1, n+1)]
for num, num_factors in enumerate(all_factors, 1):
for factor in all_factors[:num]:
weaknesses.append(weakness)
weakest = max(weaknesses)
return [weakest, weaknesses.count(weakest)]
def rectangleRotation(a, b):
points = (math.floor(n) * math.floor(m)) + (math.ceil(n) * math.ceil(m))
if math.floor(n) % 2 != math.floor(m) % 2:
# rectangleRotation(6, 4)
print(rectangleRotation(8,6))
# return "-".join(s).replace("- -", " ")
# insertDashes = lambda s: "-".join(s).replace("- -", " ")
# return "-".join(*eval(dir()[0])).replace("- -", " ")
# return re.sub("- -", " ", "-".join(*eval(dir()[0])))
# insertDashes = lambda s: re.sub('\B', '-', s)
return re.sub("\B", "-", *eval(dir()[0]))
n = sum(int(i) for i in num)
result = list(int("".join(num[:i] + num[1 + i :])) for i in range(len(num)))
for i in range(len(digits_of_n)):
if digits_of_n[i] % 2 != 0:
def longestDigitsPrefix(inputString):
for i in range(len(inputString)):
if inputString[i].isdigit():
return inputString[0:count]
# def removeDuplicateStrings(a):
# return list(OrderedDict.fromkeys(a))
# removeDuplicateStrings = lambda a: list(OrderedDict.fromkeys(a))
return list(OrderedDict.fromkeys(*eval(dir()[0])))
def extractEachKth(inputArray, k):
for i in range(len(inputArray)):
inp.append(inputArray[i])
"""Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product."""
def adjacentElementsProduct(inputArray):
# Step 1: Initially, define an empty array where we will store the products of adjacent elements from the input array.
# Step 2: Using a for-loop, we go over all entries of the input array, calculating the products of adjacent elements
# and appending them to the empty array from step 1.
for i in range(len(inputArray) - 1):
ArrayEnd.append(inputArray[i] * inputArray[i + 1])
# Step 3: We seek the largest entry in "ArrayEnd" from step 1, using the max() function.
"""After becoming famous, the CodeBots decided to move into a new building together.
Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted!
Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.
Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return
the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0).
the output should be matrixElementsSum(matrix) = 9.
example 1: There are several haunted rooms, so we'll disregard them as well as any rooms beneath them.
Thus, the answer is 1 + 5 + 1 + 2 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)
the output should be matrixElementsSum(matrix) = 9.
Note that the free room in the final column makes the full column unsuitable for bots (not just the room directly beneath it).
Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)"""
def matrixElementsSum(matrix):
# Step 1: We begin by defining the number of rows and columns inside our given matrix.
# You can conceive the number of rows as the number of nested arrays inside the main array and
# the number of columns as the number of elements in the first nested array.
# Feel free to convince yourself that this is the case by referring to the examples of matrices shown above.
# Step 2: Furthermore, create a new variable called "summ" (from summation) and set it equal to zero.
# It will be used in the following for-loop.
# Step 3: Here we have an unusual for-inside-a-for loop (compared to the one that we usually observe when dealing with matrices).
# As we are interested in the position of elements in columns (elements BELOW 0s), the outside for-loop works across all columns
# whilst the nested for-loop works across all rows.
# Step 4: If, while counting, the loop meets an element whose value is zero, the counting stops.
# Otherwise, it continues counting, each time adding the value of the i-th / j-th element to the "summ" variable, defined in step 2.
# Step 5: Therefore, we end up with the total sum of non-zero elements whose position in a column is not
# below an element of value zero.
def findEmailDomain(address):
address_spl = address.split("@")
c = [i for i in address_spl]
if len(address_spl) == 2:
if len(address_spl) == 3:
from itertools import groupby
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
personal_max = max(yourLeft, yourRight)
friend_max = max(friendsLeft, friendsRight)
sum1 = yourLeft + yourRight
sum2 = friendsLeft + friendsRight
if sum1 == sum2 and personal_max == friend_max:
def productExceptSelf(nums, m, first=True):
# uses divide and conquer approach from Khan academy!
# may need to upgrade with prime factorization
# and fast modular exponents using binary!
# make map of prime factors and their exponents (number of each factor)
# by breaking down individual array items
# remove individual values from map for each item in array (reduce number of each factor present in current item)
# convert exponent to binary and get modular exponents for each factor (see here: https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/fast-modular-exponentiation)
# finally, combine all different prime factors for the number and add to array
# reduce array by summing and final mod as shown
# left_mod = productExceptSelf(nums[0:mid], m, False)
# right_mod = productExceptSelf(nums[mid:], m, False)
output.append(productExceptSelf(arr, m, False))
left = productExceptSelf(nums[0:mid], m, False)
right = productExceptSelf(nums[mid:], m, False)
return (left * right) % m
arr = pd.read_json("./test-16.json").loc["nums", "input"]
print(productExceptSelf(arr, 9999, first=True))
# works for small cases, need to use divide and conquer according to Khan
# #first, get the number of all nums multiplied
# #get the array of modulo m elements
# fg_arr = [(largest_num/num) % m for num in nums]
# total = sum(fg_arr) % m
# def triangleExistence(t):
# return t[0] + t[1] > t[2]
# triangleExistence = lambda t: sum(t) - max(t) > max(t)
# return t[0] + t[1] > t[2]
# return sum(t) - max(t) > max(t)
a, b, c = sorted(*eval(dir()[0]))
def messageFromBinaryCode(code):
bits = [int(code[i * 8 : i * 8 + 8], 2) for i in range(len(code) // 8)]
for j in range(len(bits)):